import { fabric } from 'fabric';
import { IEditor } from '@/types/global';
import { Gradient, Pattern } from 'fabric/fabric-impl';

class HoverElementPlugin {
  canvas: fabric.Canvas;
  editor: IEditor;
  static pluginName = 'HoverElementPlugin';

  constructor(canvas: fabric.Canvas, editor: IEditor) {
    this.canvas = canvas;
    this.editor = editor;
    this.init();
  }

  init() {
    const { canvas } = this;
    let stroke = '';
    let fill: string | Pattern | Gradient = '';
    canvas.on('mouse:over', function (e) {
      if (!e.target) return;
      stroke = e.target.stroke || 'rgba(0, 0, 0, 1)';
      fill = e.target.fill || '';
      e.target.set({
        stroke: 'rgba(90, 194, 240, 1)',
      }); //e.target获取触发事件的对象
      if (e.target.type === 'textbox') {
        e.target.set({
          fill:
            fill === '' || fill === 'rgba(0, 0, 0, 0)'
              ? fill
              : 'rgba(90, 194, 240, 1)',
        });
      }
      canvas.renderAll(); //重新渲染 必须的  所有对canvas的修改，包括在其中添加删除对象，以及对象参数的修改，都需要调用渲染方法才能显示出来
    });
    canvas.on('mouse:out', function (e) {
      if (!e.target) return;
      e.target.set({
        stroke: stroke,
        fill: fill,
      });
      canvas.renderAll();
    });
  }
}
export default HoverElementPlugin;
